<?php

namespace App\Http\Controllers\Finance;

use Exception;
use App\Models\System\SysLog;
use Illuminate\Http\Request;
use App\Models\Finance\Pattern;
use App\Models\Finance\Original;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

/**
 * 薪资方案逻辑控制器
 *
 * Date: 2018/5/28
 * @author George
 * @package App\Http\Controllers
 */
class PatternController extends Controller
{
	/**
	 * 获取公司的薪资方案
	 *
	 * Date: 2018/5/28
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function index(Request $request)
	{
		$user = Auth::user();
		$paginate = $request->get('paginate', 15);

		$query = Pattern::query();
		$query->where('company_id', $user->company_id);

		return success($query->paginate($paginate));
	}

	public function show(Pattern $pattern)
	{
		return success($pattern);
	}

	/**
	 * 创建薪资方案
	 *
	 * Date: 2018/6/4
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function store(Request $request)
	{
		$attributes = $this->validate($request, [
			'name' => 'required',
			'introduction' => 'nullable',
		]);
		$user = Auth::user();

		$count = DB::table('patterns')->where([
			['company_id', '=', $user->company_id],
			['name', '=', $attributes['name']],
		])->count();

		if ($count > 0) {
			return failed('薪资方案名称已存在', 422);
		}

		$attributes['company_id'] = $user->company_id;

		try {
			DB::beginTransaction();
			$pattern = Pattern::create($attributes);
			$records = [];
			// 初始化薪资方案的计算项设置
			$originals = Original::query()->pluck('id');
			foreach ($originals as $original) {
				$records[] = [
					'company_id' => $user->company_id,
					'pattern_id' => $pattern->id,
					'original_id' => $original,
					'status' => 1
				];
			}
			DB::table('company_original_pivot')->insert($records);
			DB::commit();
			SysLog::log(Auth::user(), '薪资方案模块', '创建人员薪资方案');
			return success($pattern);
		} catch (Exception $exception) {
			DB::rollBack();
			return internalError('创建薪资失败');
		}
	}

	/**
	 * 更新薪资方案
	 *
	 * Date: 2018/6/4
	 * @author George
	 * @param Request $request
	 * @param Pattern $pattern
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function update(Request $request, Pattern $pattern)
	{
		$attributes = $this->validate($request, [
			'name' => 'required',
			'introduction' => 'nullable',
		]);

		$pattern->update($attributes);
		return updated($pattern);
	}

	/**
	 * 删除薪资方案
	 *
	 * Date: 2018/6/5
	 * @author George
	 * @param Pattern $pattern
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Exception
	 */
	public function destroy(Pattern $pattern)
	{
		$pattern->delete();
		return deleted();
	}
}
